package cn.vivi.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import cn.vivi.domain.Product;
import cn.vivi.domain.vo.QueryData;
import cn.vivi.mapper.ProductMapper;
import cn.vivi.service.ProductService;

public class ProductServiceImpl implements ProductService {

	private ProductMapper productMapper = new ProductMapper();

	@Override
	public List<Product> findAll() {
		try {
			return productMapper.findAll();
		} catch (SQLException e) {
			e.printStackTrace();
			return Collections.emptyList();
		}
	}

	@Override
	public boolean delete(String id) {
		try {
			return productMapper.delete(id);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean addProduct(Product product) {
		try {
			return productMapper.insert(product);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean updateProduct(Product product) {
		try {
			return productMapper.update(product);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public List<Product> findByQueryData(QueryData data) {
		String id = data.getClassesId();
		Double minPrice = data.getMinPrice();
		Double maxPrice = data.getMaxPrice();
		List<Product> pros = new ArrayList<Product>(30);
		try {
			if (!Objects.isNull(id)) {
				List<Product> products = productMapper.findByClassesId(id);
				pros.addAll(products);
			} else if (!Objects.isNull(minPrice) && !Objects.isNull(maxPrice)) {
				pros.addAll(productMapper.findByPrice(data));
			}
			return pros;
		} catch (SQLException e) {
			e.printStackTrace();
			return pros;
		}
	}
}
